<template>
	<view class="form-container">
    <u-sticky>
      <view class="" style="padding-top: 10rpx;background: #fff;">
        <u-subsection :list="tabList" :current="activeTab" model="button" inactiveColor="#fff" bgColor="#5c6be3" activeColor="#5c6be3" fontSize="16" @change="onTabChange"></u-subsection>
      </view>
    </u-sticky>
    <u-form
        labelPosition="left"
        :model="ruleForm"
        :rules="rules"
        labelWidth="120px"
        ref="ruleForm"
        :labelStyle="{
          height: '64rpx',
          fontSize: '28rpx'
        }"
    >
      <u-form-item v-if="activeTab === 0" label="所属车间" borderBottom ref="item1">
        <view class="text-right font-size-14 width-100-percentage">{{ ruleForm.workshopName }}</view>
      </u-form-item>
      <u-form-item v-if="activeTab === 0" label="所属工序" borderBottom ref="item1">
        <view class="text-right font-size-14 width-100-percentage">{{ ruleForm.processName }}</view>
      </u-form-item>
      <u-form-item v-if="activeTab === 0" label="下达人" borderBottom ref="item1">
        <view class="text-right font-size-14 width-100-percentage">{{ ruleForm.giveName }}</view>
      </u-form-item>
      <u-form-item v-if="activeTab === 0" label="下达时间" borderBottom ref="item1">
        <view class="text-right font-size-14 width-100-percentage">{{ ruleForm.giveTime }}</view>
      </u-form-item>
      <u-form-item v-if="activeTab === 0" label="翻改负责人" borderBottom ref="item1">
        <view @click="onSelectEmpBtn" class="flex-end-center font-size-14 width-100-percentage">
          <view :class="ruleForm.changeName ? 'color1' : 'color3'">{{ ruleForm.changeName || '请选择翻改负责人' }}</view>
          <u-icon slot="right" name="arrow-right" size="20" color="#2d8cf0"></u-icon>
        </view>
      </u-form-item>
      <u-form-item v-if="activeTab === 0" label="要求翻改日期" borderBottom ref="item1">
        <view class="text-right font-size-14 width-100-percentage">{{ ruleForm.changeDate }}</view>
      </u-form-item>
      <u-form-item v-if="activeTab === 0" labelPosition="top" label="备注" borderBottom ref="item1">
        <jk-textarea :value.sync="ruleForm.remark"></jk-textarea>
      </u-form-item>


    <!-- 产量能耗信息 -->
      <u-form-item v-if="activeTab === 1" label="通知单" borderBottom ref="item1">
        <view @click="onSelectNoticeOrderBtn" class="flex-end-center font-size-14 width-100-percentage">
          <view :class="ruleForm.noticeOrderCode ? 'color1' : 'color3'">{{ ruleForm.noticeOrderCode || '请选择通知单' }}</view>
          <u-icon slot="right" name="arrow-right" size="20" color="#2d8cf0"></u-icon>
        </view>
      </u-form-item>
      <view v-if="activeTab === 1" class="machine-table-container">
        <view class="machine-table-head">
          <u-row>
            <u-col :span="2">
              <view class="machine-table-cell-item">机台</view>
            </u-col>
            <u-col :span="6">
              <view class="">品种</view>
            </u-col>
            <u-col :span="2">
              <view class="">开台时间</view>
            </u-col>
            <u-col :span="2">
              <view class="text-right">排产数量</view>
            </u-col>
          </u-row>
        </view>
        <view class="machine-table-body" :style="{ height: `400px` }">
          <view
              v-for="(item, index) in tableData"
              :key="item.machineId"
              hover-class="machine-table-tr-hover-class"
              class="machine-table-tr"
              @longpress="onLongPress(item, index)"
          >
            <u-row>
              <u-col :span="2"><view class="machine-table-cell-item">{{ item.machineName }}</view></u-col>
              <u-col :span="6"><view class="">{{ item.productName }}</view></u-col>
              <u-col :span="2"><view class="">{{ item.time }}</view></u-col>
              <u-col :span="2"><view class="text-right">{{ item.productionQty }}</view></u-col>
            </u-row>
          </view>
        </view>
      </view>
      <view class="operation-box">
        <u-button v-if="activeTab === 1" :disabled="!ruleForm.noticeOrderCode" @click="showNoticeMachineModal = true" type="default" :customStyle="{color: '#808695'}" size="normal">
          <view class="item-gap"><u-icon name="plus" size="14" color="#808695"></u-icon></view>
          <view>添加设备</view>
        </u-button>
      </view>
    </u-form>
    <view>
      <u-button @click="onConfirmBtn" color="#2d8cf0" :loading="confirmLoading" size="large">确定</u-button>
    </view>
    <jkSelectEmpModal
        :show="showEmpModal"
        :workshop-id="ruleForm.workshopId"
        @close="onCloseOfSelectEmpModel"
        @confirm="onConfirmOfSelectEmpModel"
    ></jkSelectEmpModal>
    <jkSelectNoticeOrderModal
        :show="showNoticeOrderModal"
        :workshop-id="ruleForm.workshopId"
        @close="onCloseOfSelectNoticeOrderModel"
        @confirm="onConfirmOfSelectNoticeOrderModel"
    ></jkSelectNoticeOrderModal>
    <jkSelectNoticeMachineModal
        :show="showNoticeMachineModal"
        :notice-order-id="ruleForm.noticeOrderId"
        @close="onCloseOfSelectNoticeMachineModel"
        @confirm="onConfirmOfSelectNoticeMachineModel"
    ></jkSelectNoticeMachineModal>
    <u-modal :show="showOperationTipShow" @cancel="onCancelOfTipModal" @confirm="onConfirmOfTipModal" @close="showOperationTipShow = false" title="提示" :closeOnClickOverlay="true" :showCancelButton="true" cancel-text="删除" confirm-text="编辑">
      <view slot="default" style="width: 100%; position: relative">
        <view @click="showOperationTipShow = false" style="position: absolute; top: -40px; right: -10px;">
          <u-icon name="close" size="22" color="red"></u-icon>
        </view>
        <view class="text-center">你是要删除、编辑？</view>
        <view class="color3 font-size-12 text-center margin-top-10">（关闭请点击空白处）</view>
      </view>
    </u-modal>
    <editModal
        :show="editModalState"
        :formData="operationRowItem"
        @close="editModalState = false"
        @confirm="onConfirmOfEditModal"
    ></editModal>
  </view>
</template>

<script>
  import {
    homeMyInfo,
    prdNoticeMachineChangeOpenDetail,
    prdNoticeMachineChangeSaveWrap, processList,
    userDataWorkshops
  } from "../../../api";
  import {formatDate, formatTime, showLoading, tipBar} from "../../../utils/jk-utils";
  import jkPopup from '../../../jk-components/jk-popup';
  import jkTextarea from '../../../jk-components/jk-textarea';
  import jkTable from '../../../jk-components/jk-table';
  import jkSelectEmpModal from './components/select-emp-modal';
  import jkSelectNoticeOrderModal from './components/select-notice-order-modal';
  import jkSelectNoticeMachineModal from './components/select-notice-machine-modal';
  import editModal from './components/edit-modal';
  export default {
    components: {
      editModal,
      jkTable,
      jkPopup,
      jkTextarea,
      jkSelectEmpModal,
      jkSelectNoticeOrderModal,
      jkSelectNoticeMachineModal
    },
    data() {
			return {
        operationIndex: null,
        showOperationTipShow: false,
        operationRowItem: {},
        editModalState: false,
        showNoticeMachineModal: false,
        showNoticeOrderModal: false,
        selectMachineModalState: false,
        tableData: [],
        showEmpModal: false,
        empList: [],
        confirmLoading: false,
        activeTab: 0,
        tabList: [ '基本信息', '机台信息' ],
			  dataId: null,
        ruleForm: {
          workshopId: null,
          workshopName: '',
          processId: null,
          processName: '',
          giveId: null,
          giveName: '',
          giveTime: '',
          changeId: null,
          changeName: '',
          changeDate: '',
          noticeOrderCode: '',
          noticeOrderId: '',
        },
        rules: {}
			}
		},
		onLoad(e) {
      this.dataId = e.id;
		},
    onShow() {
      this.getDependentData();
    },
		methods: {
      onLongPress(rowItem, index) {
        this.operationRowItem = JSON.parse(JSON.stringify(this.tableData[index]));
        this.operationIndex = index;
        this.showOperationTipShow = true;
      },
      onConfirmOfTipModal() {
        this.editModalState = true;
        this.showOperationTipShow = false;
        this.operationIndex = null;
      },
      onCancelOfTipModal() {
        if (this.operationIndex || this.operationIndex === 0) {
          this.tableData.splice(this.operationIndex, 1);
          this.operationRowItem = {};
        } else {
          tipBar('none');
        }
        this.operationIndex = null;
        this.showOperationTipShow = false;
      },
      onConfirmOfEditModal(formData) {
        let cpData = JSON.parse(JSON.stringify(formData));
        this.tableData.forEach(item => {
          if (item.machineCode === cpData.machineCode) {
            this.$set(item, 'time', cpData.time);
          }
        })
        this.operationRowItem = {};
        this.editModalState = false;
      },
      onCloseOfSelectNoticeMachineModel() {
        this.showNoticeMachineModal = false;

      },
      onConfirmOfSelectNoticeMachineModel(data) {
        this.tableData = data;
        this.tableData = data.map(x => {
          x.time = '10:00';
          return x;
        });
        this.showNoticeMachineModal = false;

      },
      onSelectNoticeOrderBtn() {
        this.showNoticeOrderModal = true;
      },
      onCloseOfSelectNoticeOrderModel() {
        this.showNoticeOrderModal = false;
      },
      onConfirmOfSelectNoticeOrderModel(e) {
        this.$set(this.ruleForm, 'noticeOrderId', e.id);
        this.$set(this.ruleForm, 'noticeOrderCode', e.code);
        this.showNoticeOrderModal = false;
      },
      onCloseOfSelectEmpModel() {
        this.showEmpModal = false;
      },
      onConfirmOfSelectEmpModel(item) {
        if (Object.keys(item).length) {
          this.$set(this.ruleForm, 'changeId', item.id);
          this.$set(this.ruleForm, 'changeName', item.name);
          this.showEmpModal = false;
        } else {
          tipBar('none');
        }
      },
      onSelectEmpBtn() {
        this.showEmpModal = true;
      },
      // 将时间格式，去掉"："并转换成number,
      transformTimeToNum(val) {
        return val.split(':').join('');
      },
      onConfirmBtn() {
        if (!this.tableData.length || !this.ruleForm.changeId || !this.ruleForm.changeDate || !this.tableData.length) {
          tipBar('validator')
          return false;
        }
        this.confirmLoading = true;
        let params = JSON.parse(JSON.stringify(this.tableData)).map(x => {
          x.remark = this.ruleForm.remark;
          x.workshopName = this.ruleForm.workshopName;
          x.workshopId = this.ruleForm.workshopId;
          x.giveName = this.ruleForm.giveName;
          x.giveId = this.ruleForm.giveId;
          x.giveTime = this.ruleForm.giveTime;
          x.changeId = this.ruleForm.changeId;
          x.changeName = this.ruleForm.changeName;
          x.changeDate = this.ruleForm.changeDate;
          x.id = null;
          x.time = this.transformTimeToNum(x.time);
          return x;
        });
        prdNoticeMachineChangeSaveWrap(params).then(res => {
           this.confirmLoading = false;
           if(res.data.status === 200) {
             uni.navigateBack({ delta: 1 });
             uni.showToast({ title: '保存成功!' });
           }
        })
      },
      onTabChange(e) {
        this.activeTab = e;
      },
      getUserInfoRequest() {
        return homeMyInfo().then(res => {
          if (res.data.status === 200) {
            this.$set(this.ruleForm, 'giveId', res.data.res.id);
            this.$set(this.ruleForm, 'giveName', res.data.res.name);
            this.$set(this.ruleForm, 'giveTime', formatTime(Date.now()));
            this.$set(this.ruleForm, 'changeDate', formatDate(Date.now()));
          }
        })
      },
      getWorkshopDataRequest() {
        return userDataWorkshops().then(res => {
          if (res.data.status === 200) {
            this.$set(this.ruleForm, 'workshopId', res.data.res.defaultUserDataEntity.workshopId);
            this.$set(this.ruleForm, 'workshopName', res.data.res.defaultUserDataEntity.workshopName);
          }
        })
      },
      getProcessListRequest() {
        return processList({ enableState: 1, auditState: 3 }).then(res => {
          if (res.data.status === 200) {
            let item = res.data.res.find(x => x.code.toUpperCase() === 'XS');
            if (item) {
              this.$set(this.ruleForm, 'processId', item.id);
              this.$set(this.ruleForm, 'processName', item.name);
            }
          }
        });
      },
      async getDependentData() {
        showLoading(true);
        await this.getWorkshopDataRequest();
        await this.getProcessListRequest();
        await this.getUserInfoRequest();
        if (this.dataId) await this.getDetailRequest();
        showLoading(false);
      },
      getDetailRequest() {
        showLoading(true);
        return prdNoticeMachineChangeOpenDetail({ id: this.dataId }).then(res => {
          showLoading(false);
          if (res.data.status === 200) {
            this.ruleForm = res.data.res;
          }
        })
      }
		}
	}
</script>

<style>

</style>
<style lang="scss" scoped>
  .machine-table-tr-hover-class {
    background: rgba(45, 140, 240, .2);
  }
  .form-container {
    width: 100%;
    padding: 24rpx 32rpx;
    box-sizing: border-box;
      .machine-table-container {
        background: #f8f8f9;
        border-radius: 8rpx;
        overflow: hidden;
        .machine-table-cell-item {
          margin: 8rpx 0;
        }
        .machine-table-head {
          background: #e8eaec;
          color: #808695;
          font-size: 26rpx;
          padding: 16rpx 8rpx;
        }
        .machine-table-body {
          overflow: auto;
          .machine-table-tr {
            color: #515a6e;
            font-size: 26rpx;
            padding: 16rpx 8rpx;
            border-radius: 4rpx;
          }
        }
      }
      .operation-box {
        padding: 20rpx 0;
      }
    }
  .popup-content-box {
    padding: 32rpx;
    .popup-content-box-title {
      font-size: 34rpx;
      text-align: center;
      margin-bottom: 20rpx;
    }
  }
</style>
